import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getSign, createSign, getSignWeekday, checkTodaySigned } from './sign.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  try {
    const { user_id } = request.body;

    // 检查今天是否已经签到
    const todaySigned = await checkTodaySigned(user_id);

    if (todaySigned) {
      // 如果今天已经签到，返回本周签到记录
      const weekSigns = await getSignWeekday(user_id);
      response.send({
        msg: 'بۈگۈن يوقلىمىدىن ئۆتۈپ بولدىڭىز ~',
        signed: true,
        weekSigns
      });
    } else {
      // 如果今天还没签到，创建签到记录
      const timestamp = Date.now();
      const post = { user_id, sign_date: timestamp };

      await createSign(post);

      // 获取更新后的本周签到记录
      const weekSigns = await getSignWeekday(user_id);

      response.send({
        msg: 'يوقلىمىدىن ئۆتتىڭىز',
        signed: false,
        weekSigns
      });
    }
  } catch (error) {
    next(error);
  }
}

// 检查时间戳是否是今天（辅助函数，可选保留）
function isTimestampToday (timestamp: number): boolean {
  if (!Number.isFinite(timestamp) || timestamp < 0) return false;

  const date = new Date(timestamp);
  const targetYear = date.getFullYear();
  const targetMonth = date.getMonth() + 1;
  const targetDay = date.getDate();

  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth() + 1;
  const currentDay = now.getDate();

  return (
    targetYear === currentYear &&
    targetMonth === currentMonth &&
    targetDay === currentDay
  );
}